import { history } from 'umi';
import type { RunTimeLayoutConfig } from 'umi';
import { PageLoading } from '@ant-design/pro-components';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';

import defaultSettings from '../config/defaultSettings';
import RightContent from '@/components/RightContent';
import UnAccessiblePage from '@/components/UnAccessiblePage';
import { getUserInfo } from './services/system.service';
import StorageManager from '@/utils/StorageManager';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: Record<string, any>;
  loading?: boolean;
  fetchUserInfo?: () => Promise<Record<string, any> | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await getUserInfo();
      return msg.data;
    } catch (error) {
      history.push('/login');
    }
    return undefined;
  };
  // 如果不是登录页面，执行
  // if (history.location.pathname !== '/login') {
  //   const currentUser = await fetchUserInfo();
  //   return {
  //     fetchUserInfo,
  //     currentUser,
  //     settings: defaultSettings,
  //   };
  // }
  return {
    fetchUserInfo,
    settings: defaultSettings,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    pageTitleRender: false,
    disableContentMargin: false,
    rightContentRender: () => <RightContent />,
    onPageChange: () => {
      const { location } = history;
      const token = StorageManager.getSessionStorageSimpleSync('storage-token');
      if((location?.pathname).includes('/register'))return 
      // 没有token，跳转到登录页
      if (!token && !(location.pathname || '').includes('/login')) {
        history.push('/login');
      }
    },
    menuHeaderRender: undefined,
    // 自定义 403 页面
    unAccessible: <UnAccessiblePage />,
    ...initialState?.settings,
  };
};
